﻿Ext.extend(demo.module,{
    init: function(){  
 	  var opt={ 
	  url:'productquery'	  
	  };
	  var pageParams={start:0,limit:10};
	  Ext.reg("combobox",Ext.form.ComboBox);
	  opt.fields=[
	  {name:'id',text:'id',header:{hidden:true},ft:'hidden'},
	  {name:'addtime',text:'修改时间',header:{hidden:true}},
	  {name:'categoryName',text:'产品类型',header:{hidden:true}},	  
	  {name:'categoryid',text:'类型id',header:{hidden:true}},	 
	  {name:'image',text:'图片',header:{hidden:true,width:110,renderer:function(v,m,r){
	    return "<img src='"+ctx_path+"/image/"+v+"@small.jpg"+"' width='100px;'/>"	    
	  }}},
	  {name:'no',text:'编号',header:{renderer:function(v,m,r){
	     return ['<div style="width:100%;height:35px;line-height:35px;">',
	       '<a target="_blank" href="'+ctx_path+'/product/a/'+r.get("id")+'">'+v+"</a>",	   
	       r.get("hot")=='0'?'<sup style="color:red;font-size:12px;">hot</sup>':'',   	       
	     '</div>',
	     ].join("")	  
	  }}},	  
	  {name:'hot',text:'hot',header:{hidden:true}},
	  {name:'commodity',text:'commodity'},
	  {name:'click',text:'点击'},
	  {name:'size',text:'size'},
	  {name:'quality',text:'quality'},	
	  {name:'kpsi',text:'kpsi'},	
	  {name:'foundation',text:'foundation'},	
	  {name:'pile',text:'pile'},
	  {name:'wholesaleprice',text:'wholesaleprice'},
	  {name:'wholesaleprice1',text:'wholesaleprice1',header:{hidden:true}},
	  {name:'retailprice',text:'retailprice'},
	  {name:'retailprice1',text:'retailprice1',header:{hidden:true}},
	  {name:'paymentterm',text:'paymentterm',header:{hidden:true}},	 
	  {name:'origin',text:'origin',header:{hidden:true}}
	  ];
	  var productType={ name:'categoryid',
		    fieldLabel:'产品类型',
		    xtype:'combobox',
		    store: new Ext.data.Store({
		            proxy: new Ext.data.HttpProxy({
		                method: 'GET',
		                url:"categoryquery?limit=100"
		            }),
		            reader: new Ext.data.JsonReader({
		                root: 'root',	              
		                fields:["id","name"] 
		            })		    
			}),
			hiddenName:'categoryid',
			editable:false,
		    displayField:'name',
		    valueField:'id',
		    allowBlank:false,
		    typeAhead: true,	
		    triggerAction: 'all',
		    emptyText:'请选择分类',
		    selectOnFocus:true		   
	  };
	  
	  var metaShow=false;
	  var desShow=false;
	  function restShow()
	  {
	       metaShow=false;
	       desShow=false;  
	  }
	  
	  var maskMetas=new Ext.LoadMask(Ext.getBody(), {msg:"fetching metas data ,Please wait..."});
	  var maskDes=new Ext.LoadMask(Ext.getBody(), {msg:"fetching des data ,Please wait..."});
	  function fetchMetas(opt)
	  {	     
			 maskMetas.show();
			 Ext.Ajax.request({ 
			     method:'POST', 
			     url:'fetchmetas', 	
			     params:{pid:opt.pid},	      
			     success : function(response, request) {
			       var data=Ext.decode(response.responseText);
			       for(var i=0;i<data.length;i++)
			       {
			          opt.f.findField("meta."+data[i].name).setValue(data[i].content);
			       }
			       maskMetas.hide();     
			     }, 
			     failure : function(response, request) { 		     
			       maskMetas.hide();
			       Ext.MessageBox.alert('错误信息', "服务器异常");
			       
			     } 
		     }); 	  
	  }	 
	  
	  function fetchDes(opt)
	  {	     
			 maskDes.show();
			 Ext.Ajax.request({ 
			     method:'POST', 
			     url:'fetchdes', 		         
			     params:{pid:opt.pid},
			     success : function(response, request) {
			       var data=Ext.decode(response.responseText);
			       if(data)
			       {
			         opt.f.findField("des").setValue(data.content);
			       }
			       maskDes.hide();	     
			     }, 
			     failure : function(response, request) { 		     
			       maskDes.hide();
			       Ext.MessageBox.alert('错误信息', "服务器异常");
			       
			     } 
		     }); 	  
	  }		   
	  
	  opt.formConfig={
	     layout:'fit',		  
	     autoWidth:true,
	     items:[
	      {
	        xtype:'tabpanel',	       
	        deferredRender:false,
	        activeTab: 0,
	        listeners :{
		       tabchange:function(con,tab){
		         g.window.doLayout(true);
		         g.window.syncSize();
		       }		       
		    },
	        autoHeight:true,
            defaults:{autoHeight:true, bodyStyle:'padding:10px'}, 
            items:[
	            {
	              layout:'column',
	              title:'基础属性'             
	            },
	            {
	              title:'META 标签',
	              listeners:{
	                show:function(tab){
	                   var id=g.form.getForm().findField("id").getValue().trim();	          
	                   if(id=="")return;   
	                   if(metaShow===id)
	                   {}
	                   else
	                   { 	                      
	                      metaShow=id;
	                      fetchMetas({pid:id,f:g.form.getForm()});
	                   }
	                }
	              },
	              layout:'form',
	              defaults:{autoHeight:true, bodyStyle:'padding:2px'}, 
	              items:[
	                { 
	                   xtype:'fieldset',
	                   title:'Title',
	                   layout:'column',	                  
	                   items:[	                    
	                     {layout:'form',labelWidth:50,columnWidth:1,items:[{fieldLabel:'Content',xtype:'textfield',name:'meta.Title',anchor:'100%'}]}	                   
	                   ]  
	                },
	                { 
	                   xtype:'fieldset',
	                   title:'Author',
	                   layout:'column',	                  
	                   items:[	                    
	                     {layout:'form',labelWidth:50,columnWidth:1,items:[{fieldLabel:'Content',xtype:'textfield',name:'meta.Author',anchor:'100%'}]}	                   
	                   ]  
	                },
	                { 
	                   xtype:'fieldset',
	                   title:'Subject',
	                   layout:'column',	                  
	                   items:[	                     
	                     {layout:'form',labelWidth:50,columnWidth:1,items:[{fieldLabel:'Content',xtype:'textfield',name:'meta.Subject',anchor:'100%'}]}	                   
	                   ]  
	                },	                
	                { 
	                   xtype:'fieldset',
	                   title:'Description',
	                   layout:'column',	                  
	                   items:[	                  
	                     {layout:'form',labelWidth:50,columnWidth:1,items:[{fieldLabel:'Content',xtype:'textfield',name:'meta.Description',anchor:'100%'}]}	                   
	                   ]  
	                },	                              
	                { 
	                   xtype:'fieldset',
	                   title:'Keywords',
	                   layout:'column',	                  
	                   items:[	                  
	                     {layout:'form',labelWidth:50,columnWidth:1,items:[{fieldLabel:'Content',xtype:'textfield',name:'meta.Keywords',anchor:'100%'}]}	                   
	                   ]  
	                }             
	                	              
	              ]
	            },
	            {
	              title:'描述',
	              layout:'fit',
	              items:[{xtype:'fckeditor',name:'des',height: 350}],
	              listeners:{
	                show:function(tab){
	                   var id=g.form.getForm().findField("id").getValue().trim();	          
	                   if(id=="")return;   
	                   if(desShow===id)
	                   {}
	                   else
	                   { 	                      
	                      desShow=id;
	                      fetchDes({pid:id,f:g.form.getForm()});
	                   }
	                }
	              }
	            }
            ]
	      }
	     ]
	  };	 
	  opt.formConfig.items[0].items[0].items=[
	   {	     
	     title:'产品图片',
	     columnWidth:.6,
	     autoHeight:true,
	     layout:'fit',	    
	     xtype:'fieldset',
	     bodyStyle:'padding:3px',  
	     items:[
	       {xtype:'imagefield',uploadUrl:ctx_path+'/up',swfuploadBase:ctx_path+"/upload",id:'productimage',
	         listeners:{
	          imageload:function()
	          {
	            var win=g.window;   	         
	            win.doLayout();	            
	            win.getEl().center();	       
	          },
	          imageupload:function(data)
	          {
	             if(data.ok)
	             {	               
	               this.loadImage(ctx_path+"/image/"+data.id+"@middle.jpg");
	               g.form.getForm().findField("image").setValue(data.id);
	             }   
	             else
	             {
	               alert("上传失败！")
	             } 
	          }
	         }
	       }
	     ]
	   },
	   {
	     columnWidth:.01,
	     xtype:'fieldset',
	     border:false,
	     items:[{
	      xtype:'label'
	     }] 
	   },
	   {
	     title:'描述',
	     layout:'form',
	     columnWidth:.39,	
	     labelWidth:120,
	     xtype:'fieldset',
	     autoHeight:true,
	     defaultType:'textfield',
	     labelAlign:'right',
	     defaults:{anchor:'93%'},
	     items:[	    
	      {name:'id',xtype:'hidden'},
	      {name:'image',xtype:'hidden'},	
	      {name:'no',xtype:'hidden'},		
	      {name:'addtime',xtype:'hidden'},		     
          productType,   
		  {		
		   xtype:'combobox',
			  store: new Ext.data.SimpleStore({
			  fields: ['v','t'],data: [['0','yes'],['1','no']]}					
			),
		   fieldLabel:'<font color=red>hot</font>',
		   name:'hot',		   
		   valueField:'v',							
		   displayField: 't',							
		   typeAhead: true,
		   value:"1",				          
		   mode: 'local',
		   readOnly:true,
		   triggerAction: 'all',
		   forceSelection: true,
		   selectOnFocus:true
		  },              	 
		  {name:'commodity',fieldLabel:'commodity',allowBlank:false},
		  {name:'size',fieldLabel:'size',allowBlank:false,		 
		   xtype:'combobox',
		   editable:true,
	       displayField: 'size', 
	       valueField: 'size',        
	       typeAhead: false,         
	       triggerAction: "all",
	       minChars: 1,     
		   store: new Ext.data.Store({
		            proxy: new Ext.data.HttpProxy({
		                method: 'GET',
		                url:"sizeassit?limit=20"
		            }),
		            reader: new Ext.data.JsonReader({
		                root: 'root',	              
		                fields:["id","size"] 
		            })		    
		    })	   
		  },
		  {name:'quality',fieldLabel:'quality',allowBlank:false,		  
		   xtype:'combobox',
		   editable:true,
	       displayField: 'quality', 
	       valueField: 'quality',        
	       typeAhead: false,         
	       triggerAction: "all",
	       minChars: 1,     
		   store: new Ext.data.Store({
		            proxy: new Ext.data.HttpProxy({
		                method: 'GET',
		                url:"qualityassit?limit=20"
		            }),
		            reader: new Ext.data.JsonReader({
		                root: 'root',	              
		                fields:["id","quality"] 
		            })		    
		    })	   
		  },
		  {name:'kpsi',fieldLabel:'kpsi',allowBlank:false,		  
		   xtype:'combobox',
		   editable:true,
	       displayField: 'kpsi', 
	       valueField: 'kpsi',        
	       typeAhead: false,         
	       triggerAction: "all",
	       minChars: 1,     
		   store: new Ext.data.Store({
		            proxy: new Ext.data.HttpProxy({
		                method: 'GET',
		                url:"kpsiassit?limit=20"
		            }),
		            reader: new Ext.data.JsonReader({
		                root: 'root',	              
		                fields:["id","kpsi"] 
		            })		    
		    })	   
		  },		  
		  {name:'foundation',fieldLabel:'foundation',allowBlank:false,		  
		   xtype:'combobox',
		   editable:true,
	       displayField: 'foundation', 
	       valueField: 'foundation',        
	       typeAhead: false,         
	       triggerAction: "all",
	       minChars: 1,     
		   store: new Ext.data.Store({
		            proxy: new Ext.data.HttpProxy({
		                method: 'GET',
		                url:"foundationassit?limit=20"
		            }),
		            reader: new Ext.data.JsonReader({
		                root: 'root',	              
		                fields:["id","foundation"] 
		            })		    
		    })	   
		  },
		  {name:'pile',fieldLabel:'pile',allowBlank:false,		  
		   xtype:'combobox',
		   editable:true,
	       displayField: 'pile', 
	       valueField: 'pile',        
	       typeAhead: false,         
	       triggerAction: "all",
	       minChars: 1,     
		   store: new Ext.data.Store({
		            proxy: new Ext.data.HttpProxy({
		                method: 'GET',
		                url:"pileassit?limit=20"
		            }),
		            reader: new Ext.data.JsonReader({
		                root: 'root',	              
		                fields:["id","pile"] 
		            })		    
		    })	   
		  },		  			 
		  {name:'wholesaleprice',fieldLabel:'wholesale price(ft)',xtype:'numberfield',allowBlank:false},
		  {name:'wholesaleprice1',fieldLabel:'wholesale price(cm)',xtype:'numberfield',allowBlank:false},
		  {name:'retailprice',fieldLabel:'retail price(ft)',xtype:'numberfield',allowBlank:false},
		  {name:'retailprice1',fieldLabel:'retail price(cm)',xtype:'numberfield',allowBlank:false},
		  {name:'paymentterm',xtype:'textarea',height:40,fieldLabel:'paymentterm',allowBlank:false},	 
		  {name:'origin',xtype:'textarea',height:40,fieldLabel:'origin',allowBlank:false}
	     ]	     
	   }
	  ];
	  opt.windowConfig={width:850};	  
	  opt.gridConfig={};	
	  opt.gridConfig.tbar=[
	   {text:'添加',iconCls:'add',handler:function(x){
	     this.window.findByType("tabpanel")[0].activate(0);
	     var load=false;
	     if(this.window.el)
	     {
	       load=true;
	     }
	     this.window.setTitle(x);
	     this.window.show();
	     this.window.center();
	     if(load){Ext.getCmp("productimage").loadDefaultImage();}
	     
	   }},
	   {
	     text:'相似添加',iconCls:'add',handler:function(x){	
	       this.window.findByType("tabpanel")[0].activate(0);       
	       this.window.setTitle(x);
	       this.edit();	
	       this.window.center();
	       var id=this.form.getForm().findField("id").getValue();
	       this.form.getForm().findField("id").setValue("");
	       this.form.getForm().findField("image").setValue("");
	       this.form.getForm().findField("no").setValue("");
	       Ext.getCmp("productimage").loadDefaultImage();
	       var Record=Ext.data.Record.create([
		         {name: 'id', mapping: 'id'},
		         {name: 'name', mapping: 'name'}		         
		       ]);
		   var cr=this.getSelection();  
		   var r=new Record({id:cr.get("categoryid"),name:cr.get("categoryName")});   	      
	       var combox=this.form.getForm().findField("categoryid");
	       combox.getStore().add(r);
	       combox.setValue(cr.get("categoryid"));	  
	       fetchDes({pid:id,f:this.form.getForm()});     
	       fetchMetas({pid:id,f:this.form.getForm()});     
	     }	     
	   },
	   {
	     text:'修改',iconCls:'edit',handler:function(x)
	     {
	       restShow();
	       this.window.findByType("tabpanel")[0].activate(0);
	       this.window.setTitle(x);
	       this.edit();	 
	       this.window.center();
	       var id=this.form.getForm().findField("image").getValue();	      
	       Ext.getCmp("productimage").loadImage(ctx_path+"/image/"+id+"@middle.jpg");
	       var Record=Ext.data.Record.create([
		         {name: 'id', mapping: 'id'},
		         {name: 'name', mapping: 'name'}		         
		       ]);
		   var cr=this.getSelection();  
		   var r=new Record({id:cr.get("categoryid"),name:cr.get("categoryName")});  
	       var combox=this.form.getForm().findField("categoryid");
	       combox.getStore().add(r);
	       combox.setValue(cr.get("categoryid"));	       
	     }
	   },
	   {
	     text:'删除',iconCls:'delete',handler:function(x)
	     {	       
	       this.del(function(rs){
	         var iarray=[];
	         for(var i=0;i<rs.length;i++)
	         {
	            iarray.push(rs[i].get("id"));
	         }	       
	         this.postJson({
	           url:'deleteproduct',
	           params:{product:{id:iarray.join("/")}}
	         })
	       })
	     }	   
	   },
	   '->',
	   '-',
	   Ext.apply(Ext.apply({},productType),{
	    xtype:'clearablecombobox',
	    listeners:{
	      select :function(t,r){
	         g.grid.getStore().baseParams["product.categoryid"]=r.get("id");
	         g.grid.getStore().reload();
	      },
	      afterclear:function()
	      {
	         g.grid.getStore().baseParams["product.categoryid"]='';
	         g.grid.getStore().reload();	        
	      } 
	    },
	    allowBlank:true,
	    width:120
	   }),
	   '-',
	   {
		   xtype:'searchfield',		   
		   paramName:'product.no',
		   defaultParams:pageParams,
		   width:120,
		   emptyText:'search NO.',
		   listeners:{
		    usestore:function(){
		      this.store=g.ds;
		    }
		   }
		}	      
	  ];  
     
     opt.gridConfig.bbar={pageSize:pageParams.limit};     
	 var g=new Ext.fay.ui.CURDGrid(opt);
	 g.on("save",function(values){
	    if(this.isValid())
	    {
	      var size=this.form.getForm().findField("size").getRawValue();//fix the bug of no value for getValue
	      var quality=this.form.getForm().findField("quality").getRawValue();
	      var hot=this.form.getForm().findField("hot").getValue();	 	     
	      values.size=size;
	      values.quality=quality;
	      values.hot=hot;
	      var des=this.form.getForm().findField("des").getValue().trim();	    
	      if(des=="<br />")
	      {
	        des="";// no modified
	      }	     
	      values.des=des;	    
	      values.meta={
	       Title:this.form.getForm().findField("meta.Title").getValue(),
	       Author:this.form.getForm().findField("meta.Author").getValue(),
	       Subject:this.form.getForm().findField("meta.Subject").getValue(),
	       Description:this.form.getForm().findField("meta.Description").getValue(),
	       Keywords:this.form.getForm().findField("meta.Keywords").getValue()
	      };
	      this.postJson({
	       url:'saveproduct',
	       params:{product:values}
	      })
	    }
	 });  
	 this.main.add(g.grid);
     this.main.doLayout(); 
     g.ds.reload({params:pageParams});
   }
});